import { useI18n } from '@/hooks/web/useI18n'
import { reactive, ref } from 'vue'
import { CrudSchema } from '@/hooks/web/useCrudSchemas'
import { useValidator } from '@/hooks/web/useValidator'
import { SchemaConfig } from '@/api/global/types'
// import { SelectedItem, useTableDialogStore } from '@/store/modules/tableDialog'
import { ElTag, ElSwitch, ElMessageBox } from 'element-plus'
// import { Close } from '@element-plus/icons-vue'
import { statusApi } from '@/api/logisticsRules'
import { useEventBus } from '@/hooks/event/useEventBus'
const { t } = useI18n()
const { required } = useValidator()
const { emit } = useEventBus()

interface Option {
  label: string
  value: string | number // 具体取决于你的数据
}

// 通用选项生成函数
const createOptions = (enumObject: { [key: string]: string }): Option[] => {
  return Object.keys(enumObject).map((key) => ({
    label: enumObject[key],
    value: parseInt(key, 10)
  }))
}

export default function (schemaConfig: SchemaConfig) {
  // 字段
  const toNationOption = reactive(createOptions(schemaConfig.fieldEnum?.to_nation || {}))
  const warehouseOption = reactive(createOptions(schemaConfig.fieldEnum?.warehouse || {}))
  const logisticsCompanyOption = reactive(
    createOptions(schemaConfig.fieldEnum?.logistics_company || {})
  )
  const termsOption = reactive(createOptions(schemaConfig.fieldEnum?.terms || {}))
  const freightTagOption = reactive(createOptions(schemaConfig.fieldEnum?.freight_tag || {}))
  const modelOption = reactive(createOptions(schemaConfig.fieldEnum?.model || {}))
  const statusOption = reactive(createOptions(schemaConfig.fieldEnum?.status || {}))

  //product 弹窗store
  // const productTableDialogStore = useTableDialogStore(schemaConfig.tableDialogStoreID)

  const crudSchemas = reactive<CrudSchema[]>([
    {
      field: 'selection',
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      detail: {
        hidden: true
      },
      table: {
        type: 'selection'
      }
    },
    {
      field: 'id',
      label: t('logisticsRules.id'),
      // type: 'index',
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      detail: {
        hidden: true
      }
    },
    {
      field: 'rule_name',
      label: t('logisticsRules.rule_name'),
      search: {
        component: 'Input'
      },
      form: {
        component: 'Input',
        formItemProps: {
          rules: [required()]
        },
        colProps: {
          span: 24
        }
      },
      detail: {
        span: 24
      }
    },
    {
      field: 'logistics_company',
      label: t('logisticsRules.logistics_company'),
      form: {
        component: 'Select',
        componentProps: {
          filterable: true,
          options: logisticsCompanyOption
        },
        formItemProps: {
          rules: [required()]
        }
      },
      search: {
        hidden: true
      },
      detail: {
        slots: {
          default: (data: any) => {
            return data.logistics_company_object?.name ?? ''
          }
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return data.row.logistics_company_object.name
          }
        }
      }
    },
    // {
    //   field: 'product_id',
    //   label: t('logisticsRules.product_id'),
    //   form: {
    //     component: 'Input',
    //     formItemProps: {
    //       rules: [
    //         // required(),
    //         {
    //           validator: (_rule, _value, callback) => {
    //             if (
    //               !productTableDialogStore.selectedItems ||
    //               productTableDialogStore.selectedItems.length === 0
    //             ) {
    //               callback(new Error('该项为必填项'))
    //               // callback()
    //             } else {
    //               callback()
    //             }
    //           },
    //           trigger: 'click'
    //         }
    //       ]
    //     },
    //     componentProps: {
    //       class: 'invisible-input',
    //       readonly: true,
    //       slots: {
    //         prefix: () => {
    //           if (
    //             productTableDialogStore.selectedItems &&
    //             productTableDialogStore.selectedItems.length > 0
    //           ) {
    //             return productTableDialogStore.selectedItems.map((item: SelectedItem) => (
    //               <ElButton
    //                 size="small"
    //                 type="success"
    //                 plain
    //                 onClick={() => productTableDialogStore.removeItem(item.id)}
    //               >
    //                 {item.title}
    //                 <ElIcon>
    //                   <Close />
    //                 </ElIcon>
    //               </ElButton>
    //             ))
    //           } else {
    //             // 处理selectedItems为空的情况，可能是返回null或者渲染一些提示信息
    //             return null
    //           }
    //         },
    //         suffix: () => {
    //           return (
    //             <ElButton
    //               class="input-button"
    //               size="small"
    //               type="primary"
    //               plain
    //               onClick={() => {
    //                 const { allSchemas } = useCrudSchemas(
    //                   schemaConfig.tableDialogCurdSchema ? schemaConfig.tableDialogCurdSchema : []
    //                 )
    //                 productTableDialogStore.openDialog()
    //                 productTableDialogStore.setSchema(allSchemas)
    //               }}
    //             >
    //               {t('customer.choose')}
    //             </ElButton>
    //           )
    //         }
    //       }
    //     }
    //   },
    //   search: {
    //     component: 'Input',
    //     formItemProps: {
    //       rules: [
    //         {
    //           validator: (_rule, _value, callback) => {
    //             if (
    //               !productTableDialogStore.selectedItems ||
    //               productTableDialogStore.selectedItems.length === 0
    //             ) {
    //               // callback(new Error('该项为必填项'))
    //               callback()
    //             } else {
    //               callback()
    //             }
    //           },
    //           trigger: 'click'
    //         }
    //       ]
    //     },
    //     componentProps: {
    //       class: 'invisible-input',
    //       readonly: true,
    //       slots: {
    //         prefix: () => {
    //           if (
    //             productTableDialogStore.selectedItems &&
    //             productTableDialogStore.selectedItems.length > 0
    //           ) {
    //             return productTableDialogStore.selectedItems.map((item: SelectedItem) => (
    //               <ElButton
    //                 size="small"
    //                 type="success"
    //                 plain
    //                 onClick={() => productTableDialogStore.removeItem(item.id)}
    //               >
    //                 {item.title}
    //                 <ElIcon>
    //                   <Close />
    //                 </ElIcon>
    //               </ElButton>
    //             ))
    //           }
    //         },
    //         suffix: () => {
    //           return (
    //             <ElButton
    //               class="input-button"
    //               size="small"
    //               type="primary"
    //               plain
    //               onClick={() => {
    //                 const { allSchemas } = useCrudSchemas(
    //                   schemaConfig.tableDialogCurdSchema ? schemaConfig.tableDialogCurdSchema : []
    //                 )
    //                 productTableDialogStore.openDialog()
    //                 productTableDialogStore.setSchema(allSchemas)
    //               }}
    //             >
    //               {t('customer.choose')}
    //             </ElButton>
    //           )
    //         }
    //       }
    //     }
    //   },
    //   detail: {
    //     slots: {
    //       default: (data: any) => {
    //         return data.product_object?.cname ?? ''
    //       }
    //     }
    //   },
    //   table: {
    //     headerAlign: 'center',
    //     align: 'center',
    //     slots: {
    //       default: (data: any) => {
    //         return data.row.product_object.cname
    //       }
    //     }
    //   }
    // },
    {
      field: 'shipping_warehouse',
      label: t('logisticsRules.shipping_warehouse'),
      search: {
        hidden: true
      },
      form: {
        formItemProps: {
          rules: [required()]
        },
        component: 'Select',
        componentProps: {
          filterable: true,
          options: warehouseOption
        }
      },
      detail: {
        slots: {
          default: (data: any) => {
            return data.shipping_warehouse_object?.name ?? ''
          }
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return data.row.shipping_warehouse_object.name
          }
        }
      }
    },
    {
      field: 'to_nation',
      label: t('logisticsRules.to_nation'),
      search: {
        hidden: true
      },
      form: {
        formItemProps: {
          rules: [required()]
        },
        component: 'Select',
        componentProps: {
          filterable: true,
          // multiple: true, // 开启,
          options: toNationOption
        }
      },
      detail: {
        slots: {
          default: (data: any) => {
            return data.to_nation_object?.name ?? ''
          }
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return data.row.to_nation_object.name
          }
        }
      }
    },

    {
      field: 'terms',
      label: t('logisticsRules.terms'),
      search: {
        component: 'Select',
        componentProps: {
          filterable: true,
          options: termsOption
        }
      },
      form: {
        component: 'Select',
        formItemProps: {
          rules: [required()]
        },
        componentProps: {
          filterable: true,
          options: termsOption
        }
      },
      detail: {
        slots: {
          default: (data: any) => {
            return data.terms_value
          }
        }
      },
      table: {
        slots: {
          default: (data: any) => {
            return data.row.terms_value
          }
        }
      }
    },
    {
      field: 'freight',
      label: t('logisticsRules.freight'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        formItemProps: {
          rules: [required()]
        },
        value: 0
      }
    },
    {
      field: 'freight_item',
      label: t('logisticsRules.freight_item'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        formItemProps: {
          // rules: [required()]
        },
        value: 0
      }
    },
    {
      field: 'freight_tag',
      label: t('logisticsRules.freight_tag'),
      search: {
        component: 'Select',
        componentProps: {
          filterable: true,
          options: freightTagOption
        }
      },
      form: {
        component: 'Select',
        componentProps: {
          filterable: true,
          options: freightTagOption
        }
      },
      detail: {
        slots: {
          default: (data: any) => {
            return data.freight_tag_value
          }
        }
      },
      table: {
        slots: {
          default: (data: any) => {
            return data.row.freight_tag_value
          }
        }
      }
    },

    {
      field: 'model',
      label: t('logisticsRules.model'),
      form: {
        component: 'Select',
        componentProps: {
          options: modelOption
        }
      },
      search: {
        component: 'Select',
        componentProps: {
          options: modelOption,
          style: {
            width: '100%'
          }
        }
      },
      detail: {
        slots: {
          default: (data: any) => {
            return data.model_value
          }
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return data.row.model_value
          }
        }
      }
    },

    // {
    //   field: 'weight_lower',
    //   label: t('logisticsRules.weight_lower'),
    //   search: {
    //     hidden: true
    //   },
    //   form: {
    //     component: 'Input',
    //     value: 0
    //   }
    // },
    // {
    //   field: 'weight_upper',
    //   label: t('logisticsRules.weight_upper'),
    //   search: {
    //     hidden: true
    //   },
    //   form: {
    //     component: 'Input',
    //     value: 0
    //   }
    // },
    {
      field: 'transfer_fee',
      label: t('logisticsRules.transfer_fee'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        value: 0
      }
    },
    {
      field: 'single_fee',
      label: t('logisticsRules.single_fee'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        value: 0
      }
    },
    {
      field: 'magnetic_inspection_fee',
      label: t('logisticsRules.magnetic_inspection_fee'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        value: 0
      }
    },
    {
      field: 'customs_declaration_fee',
      label: t('logisticsRules.customs_declaration_fee'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        value: 0
      }
    },
    {
      field: 'insurance_rate',
      label: t('logisticsRules.insurance_rate'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        value: 0
      }
    },
    // {
    //   field: 'insurance_fee',
    //   label: t('logisticsRules.insurance_fee'),
    //   search: {
    //     hidden: true
    //   },
    //   form: {
    //     component: 'Input',
    //     value: 0
    //   }
    // },
    // {
    //   field: 'level',
    //   label: t('logisticsRules.level'),
    //   search: {
    //     hidden: true
    //   },
    //   form: {
    //     component: 'Input',
    //     value: 0
    //   }
    // },
    {
      field: 'status',
      fixed: 'right',
      width: '80',
      label: t('logisticsRules.status'),
      form: {
        component: 'Select',
        componentProps: {
          options: statusOption
        }
      },
      search: {
        component: 'Select',
        componentProps: {
          options: statusOption,
          style: {
            width: '100%'
          }
        }
      },
      detail: {
        slots: {
          default: (data: any) => {
            return (
              <ElTag type={data.status === 0 ? 'warning' : 'success'}>{data.status_value}</ElTag>
            )
          }
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            const originalStatus = data.row.status // 保存原始状态
            const confirmationMessage = data.row.status === 1 ? '确定要关闭吗?' : '确定要开启吗?'
            const handleSwitchChange = () => {
              ElMessageBox.confirm(confirmationMessage, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              })
                .then(async () => {
                  const loading = ref(false)
                  loading.value = true
                  const res = await statusApi({
                    ids: data.row.id.toString(),
                    status: data.row.status === 1 ? 0 : 1
                  })
                    .catch(() => {})
                    .finally(() => {
                      loading.value = false
                    })
                  if (res) {
                    emit('getList', 'editor')
                  }
                })
                .catch(() => {
                  data.row.status = originalStatus
                })
            }
            return (
              <ElSwitch
                v-model={data.row.status}
                active-value={1}
                inactive-value={0}
                // active-text={statusOption[1].label}
                // inactive-text={statusOption[0].label}
                active-color="#13ce66"
                inactive-color="#ff4949"
                onChange={handleSwitchChange}
              ></ElSwitch>
            )
          }
        }
      }
    },
    {
      field: 'create_time',
      label: t('logisticsRules.create_time'),
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      table: {
        headerAlign: 'center',
        align: 'center'
      }
    },
    {
      field: 'creator',
      label: t('logisticsRules.creator'),
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      detail: {
        slots: {
          default: (data: any) => {
            return data.creator_object?.cname ?? ''
          }
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return data.row.creator_object?.cname
          }
        }
      }
    },
    {
      field: 'update_time',
      label: t('logisticsRules.update_time'),
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      table: {
        hidden: true
      }
    },
    {
      field: 'updater',
      label: t('logisticsRules.updater'),
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      detail: {
        slots: {
          default: (data: any) => {
            return data.updater_object?.cname ?? ''
          }
        }
      },
      table: {
        hidden: true
        // headerAlign: 'center',
        // align: 'center',
        // slots: {
        //   default: (data: any) => {
        //     return data.row.updater_object?.cname
        //   }
        // }
      }
    },
    {
      field: 'action',
      width: '260px',
      label: t('tableDemo.action'),
      fixed: 'right',
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      detail: {
        hidden: true
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return schemaConfig.actionButtonsTemplate?.template(data) ?? null
          }
        }
      }
    }
  ])

  return {
    crudSchemas
  }
}
